package com.bos.util;

import com.bos.domain.Kabupaten;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.IOException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Latief
 * Date: 5/8/11
 * Time: 8:41 PM
 * To change this template use File | Settings | File Templates.
 */
public final class UrlUtil {

    private final static String hostKabupatenUrl = "http://{host}:{port}/kab/";
    public final static String HOST_PROPINSI_URL = "http://localhost:8080/prop/";

    public static String getKabupatenHostUrl(Kabupaten host) {
        if (host == null)
            return null;

        if (host.getHost() == null || host.getPort() <= 0)
            return null;

        return hostKabupatenUrl.replace("{host}", host.getHost()).replace("{port}", host.getPort() + "");
    }

    /**
     * Fungsi untuk mengecek sejumlah host sedang available atau tidak. Jika ada host yang tidak available akan
     * bernilai false. true jika semua hosts available.
     *
     * @param hosts
     * @return
     */
    public static boolean isHostsAvailable(List<Kabupaten> hosts) {
        boolean available = true;
        for (Kabupaten host : hosts) {
            if (!isHostAvailable(host)) {
                available = false;
                break;
            }
        }
        return available;
    }

    public static boolean isHostAvailable(Kabupaten host) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(getKabupatenHostUrl(host));
        try {
            HttpResponse response = httpClient.execute(httpGet);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static boolean isPropHostAvailable() {
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(HOST_PROPINSI_URL);
        try {
            HttpResponse response = httpClient.execute(httpGet);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
}
